import React, { PureComponent } from 'react'
import { connect } from 'dva';

import { Table, Divider, Popconfirm, Modal, Icon, message } from 'antd';
import QRCode from 'qrcode.react';
import Form from './components/SearchForm';

export interface IProps {
  dispatch?: Function;
  children?: React.ReactNode;
  loading?: boolean;
  buttons?: Array<any>;
  cond?: any;
  list?: {
    data: Array<any>;
    dataCnt: number
  }
}

interface IState {
  current: number;
  downVisible: boolean;
  selectedRowKeys: Array<any>;
  downQrCode: string;
  belongName: string;
}

const ONE_PAGE_SIZE = 10;

@connect(({ qrcode_blank = {}, menu, loading }) => ({
  list: qrcode_blank.list || {},
  dict: qrcode_blank.dict || {},
  cond: qrcode_blank.cond || {},
  buttons: menu.buttons,
  loading: loading.effects['qrcode_blank/queryPage']
}))
class QrcodeBlack extends PureComponent<IProps, IState> {

  readonly state: IState = {
    current: 1,
    selectedRowKeys: [],
    downVisible: false,
    downQrCode: '',
    belongName: ''
  }

  queryData = (pageNum = 1) => {
    const { dispatch } = this.props;

    dispatch({ type: 'qrcode_blank/queryPage', payload: { pageNum } })
  }

  initCurrent = () => {
    this.setState({
      current: 1
    })
  }

  componentDidMount() {
    this.queryData();
  }

  export = e => {
    
    if (this.state.selectedRowKeys.length === 0) {
      message.warn('请选择导出的二维码');
      return;
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'qrcode_blank/exportQrcode',
      payload: {
        ids: this.state.selectedRowKeys,
        name: '二维码导出',
      }
    })
  }

  downHandleOk = () => {
    this.setState({
      downVisible: false
    });
  };

  downHandleCancel = () => {
    this.setState({
      downVisible: false
    });
  };

  convertCanvasToImage = () => {
    const downQrCode: any = document.getElementById('downQrCode');
    const url = downQrCode.toDataURL("image/png");
    const a = document.createElement('a');
    const event = new MouseEvent('click');
    a.download = this.state.belongName;
    a.href = url;
    a.dispatchEvent(event);
    this.setState({
      downVisible: false
    })
  };

  onSelectChange = (selectedRowKeys) => {

    this.setState({ selectedRowKeys });
  };

  downloadFn = (qrcode) => { // 下载二维码
    this.setState({
      downQrCode: qrcode.code,
      belongName: qrcode.belongName,
      downVisible: true
    });
  };

  onShowSizeChange = (current:Number, pageSize:Number) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `qrcode_blank/updateCond`, payload: cond})
  }

  remove = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'qrcode_blank/remove',
      payload: id
    }).then(() => {
      this.queryData()
    });
  };

  render() {
    const { selectedRowKeys } = this.state;
    const { list, buttons = [] } = this.props;
    const { data = [], dataCnt } = list;
    const btnList = {};
    buttons.forEach(item => {
      btnList[item.name] = item.name
    });

    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: item.id,
      ...item
    })
    ) : []
    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({ current })
        this.queryData(current)
      },
    };
    const columns = [{
      title: '二维码地址',
      dataIndex: 'code',
    }, {
      title: '状态',
      dataIndex: 'bindStatusName',
    }, {
      title: '操作时间',
      dataIndex: 'createTime',
    }, {
      title: '操作人员',
      dataIndex: 'creatorName',
    }, {
      title: '操作', key: 'x', render: (record) => {
        return (
          <div style={{ display: 'flex' }}>
            <span
              onClick={() => { this.downloadFn(record) }}
              style={{ 'cursor': 'pointer', 'color': '#0880DF' }}>
              下载
            </span>
            <Divider type="vertical" />
            <Popconfirm 
              title="请确认是否删除?" 
              onConfirm={() => { this.remove(record.id) }} 
              okText="确定" 
              cancelText="取消"
              icon={<Icon type="exclamation-circle" />}
            >
              <a>删除</a>
            </Popconfirm>
          </div>
        )
      }
    }];

    const rowSelection = {
      onChange: this.onSelectChange,
      selectedRowKeys,
    };

    return (
      <div>
        <Form current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['新增']} export={this.export}/>
        <Table
          columns={columns}
          pagination={pagination}
          dataSource={ans}
          bordered
          rowSelection={rowSelection}
          loading={this.props.loading}
        />
        <Modal
          title="二维码下载"
          visible={this.state.downVisible}
          onOk={this.downHandleOk}
          onCancel={this.downHandleCancel}
          footer={null}
        >
          <div style={{ 'textAlign': 'center', 'marginBottom': '30px' }}>
            <QRCode value={this.state.downQrCode} width="200px" height="200px" id="downQrCode" />
          </div>
          <div style={{ 'textAlign': 'right', 'paddingLeft': '20px' }}>
            <p style={{ 'display': 'inline-block', 'textAlign': 'center' }}>
              <Icon type="download" style={{ 'marginRight': '6px' }} />
              <span style={{ 'fontSize': '12px', 'color': '#0880DF', 'cursor': 'pointer' }} onClick={() => { this.convertCanvasToImage() }}>点击下载</span>
            </p>
          </div>
        </Modal>
      </div>
    );
  }
}

export default QrcodeBlack;
